/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { message, Switch, Space, Typography } from 'antd';
import { TreeSelect } from 'antd';
import ProForm, {
  ModalForm,
  ProFormCheckbox,
  ProFormDependency,
  ProFormTreeSelect,
  ProFormInstance,
  ProFormDigit,
} from '@ant-design/pro-form';
import type { OptionsType } from '@/components/_pages/jdk/addLeague/_utils/type';
import {
  getBrandList,
  getSourceList,
  getLeaguePublishInfo,
  getLeaguePublishRemove,
  getLeaguePublishSetting,
} from '@/services/jdk/shield';
import React, { useEffect, useRef, useState } from 'react';

interface PriorityProps {
  league_id?: string;
}

interface PriorityInfo {
  league_id: string;
  source_brand: string[];
  advance_delivery: {
    [name: string]: string;
  };
  created_at: string;
  updated_at: string;
}

const { Paragraph } = Typography;

const KbEditForm: React.FC<PriorityProps> = (props) => {
  const formRef = useRef<ProFormInstance>(null);
  const { SHOW_PARENT } = TreeSelect;
  const { league_id } = props;
  const [brands, setBrands] = useState<OptionsType[]>([]);
  const [source, setSource] = useState<OptionsType[]>([]);
  const [status, setStatus] = useState<boolean>(false);
  const [record, setRecord] = useState<PriorityInfo>();
  const [visible, setVisible] = useState<boolean>(false);

  const handleOpenModal = () => setVisible(true);
  const handleCloseModal = () => setVisible(false);
  const handleSwitchChange = (checked: boolean) => {
    setStatus(checked);
    if (checked) {
      handleOpenModal();
    } else {
      getLeaguePublishRemove({ league_id }).then((res) => {
        const { code, msg } = res;
        if (code == 0) {
          message.success('操作成功');
          handleCloseModal();
        } else {
          message.error(msg);
        }
      });
    }
  };

  const formatRender = (data: OptionsType[], value: string) =>
    data.find((item) => item.value == value)?.label || '';
  const onFinish = async (values: any) => {
    const { source_brand, platform } = values;
    const advance_delivery = {};
    platform.forEach((item: string) => {
      if (values[item]) {
        advance_delivery[item] = values[item];
      }
    });
    const { code, msg } = await getLeaguePublishSetting({
      source_brand,
      advance_delivery,
      league_id,
    });
    if (code == 0) {
      message.success(msg);
      handleCloseModal();
    } else {
      message.error(msg);
    }
  };

  const getBrandsList = () => {
    getBrandList({}).then((data) => setBrands(data));
    getSourceList({}).then((data) => setSource(data));
  };
  const getDetail = () => {
    getLeaguePublishInfo({ league_id }).then(({ data }) => {
      setRecord(data);
      setStatus(!!data.league_id);
      const { source_brand, advance_delivery } = data;
      formRef.current?.setFieldsValue({
        source_brand,
        platform: Object.keys(advance_delivery),
        ...advance_delivery,
      });
    });
  };

  useEffect(() => {
    getBrandsList();
    if (league_id) getDetail();
  }, [league_id, visible]);

  return (
    <>
      <Space direction='vertical'>
        <div>运力优先级</div>
        <Paragraph type='secondary' style={{ margin: 0 }}>
          {status ? (
            <Space direction='horizontal'>
              {Object.keys(record?.advance_delivery || {}).map((item) => (
                <Paragraph key={item} type='secondary' style={{ margin: 0 }}>
                  {formatRender(brands, item)}
                </Paragraph>
              ))}
              <a onClick={handleOpenModal}>去设置&gt;</a>
            </Space>
          ) : (
            '暂未设置'
          )}
        </Paragraph>
      </Space>
      <div style={{ textAlign: 'right' }}>
        <Switch checked={status} onChange={handleSwitchChange} />
      </div>
      <ModalForm<PriorityInfo>
        title='运力优先级设置'
        formRef={formRef}
        visible={visible}
        onFinish={onFinish}
        modalProps={{
          onCancel: handleCloseModal,
          destroyOnClose: true,
          bodyStyle: { height: 400, overflowY: 'auto' },
        }}
      >
        <ProFormTreeSelect
          label='选择适用外卖平台'
          name='source_brand'
          placeholder='请选择适用外卖平台'
          rules={[{ required: true, message: '请选择外卖平台' }]}
          allowClear
          width={330}
          request={async () => [
            {
              label: '全部',
              value: 'all',
              children: source,
            },
          ]}
          fieldProps={{
            showArrow: false,
            showSearch: false,
            showCheckedStrategy: SHOW_PARENT,
            treeCheckable: true,
          }}
        />
        <ProForm.Item
          label='点击运力品牌，可将其设置为优先级运力，再次点击则取消优先级'
          name='platform'
          rules={[{ required: true, message: '请选择运力品牌' }]}
        >
          <ProFormCheckbox.Group options={brands} />
        </ProForm.Item>
        <ProForm.Item label='运力优先级'>
          <ProFormDependency name={['platform']}>
            {({ platform = [] }) =>
              platform.map((item: string, index: number) => (
                <ProFormDigit
                  key={item}
                  name={item}
                  rules={[
                    { required: true, message: '请输入品牌设置提前时间' },
                    {
                      pattern: /^([1-9]|[1-5][0-9]|60|[1-5][0-9][0-9]|600)$/,
                      message: '优先时间请输入1-600s 整数',
                    },
                  ]}
                  addonBefore={
                    <Space direction='horizontal'>
                      <div>{index + 1} </div>
                      <div>{formatRender(brands, item)}</div>
                      <div>设置提前时间</div>
                    </Space>
                  }
                  addonAfter={'s'}
                />
              ))
            }
          </ProFormDependency>
        </ProForm.Item>
      </ModalForm>
    </>
  );
};

export default KbEditForm;
